//
//  ZHCacheTools.swift
//  ZZLeSay
//
//  Created by 赵正华 on 16/9/14.
//  Copyright © 2016年 赵正华. All rights reserved.
//

import UIKit

class ZHCacheTools: NSObject {

    lazy var shareInstance = ZHCacheTools()
    
    //获取系统缓存大小
   class func getSystemCacheSize() -> String?{
        //定义缓存大小变量
        var cacheSize : Float = 0
        //获取缓存路径
        let totalPath = NSHomeDirectory().stringByAppendingString("/Library/Caches")
        
        //创建文件管理对象
        let mananger = NSFileManager.defaultManager()
        if mananger.fileExistsAtPath(totalPath) {
        //获取缓存路径下面的所有子路径
        let subPaths = try? mananger.subpathsOfDirectoryAtPath(totalPath)
        
        //遍历子路径,获取所有文件
        for subPath in subPaths! {
            let filePath = totalPath + "/\(subPath)"
            let size = try? mananger.attributesOfItemAtPath(filePath)
            let fileSize = size!["NSFileSize"] as! Float
            cacheSize += fileSize
        }
    }
        let totalString = NSString(format: "%.2f MB", cacheSize / 1024.0 / 1024.0 ) as String
        return totalString
    }
    //清除系统缓存
   class func cleanSystemCache() ->Bool {
        //定义缓存大小变量
        var result : Bool = true
        //获取缓存路径
        let totalPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
        
        //创建文件管理对象
        let mananger = NSFileManager.defaultManager()
        if mananger.fileExistsAtPath(totalPath!) {
            //获取缓存路径下面的所有子路径
            let subPaths =  mananger.subpathsAtPath(totalPath!)
            //遍历子路径,获取所有文件
            for subPath in subPaths! {
                let path = totalPath?.stringByAppendingString("/\(subPath)")
                do{
                    try mananger.removeItemAtPath(path!)
                }catch{
                   result = false
                 }
            }
        }
        return result
    }
}
